/*
 * @Date: 2021-11-16 17:20:06
 * @Version: 0.0.1
 * @Author: chenhengling
 * @Description: 更新项目模板
 * @LastEditTime: 2021-11-17 13:50:45
 * @LastEditors: chenhengling
 */
const path = require('path');
const fs = require('fs');
const { deleteFile } = require('./index');

function main(localPath, packageJson, deleteFiles = []) {
  return new Promise((resolve, reject) => {
    try {
      // 更新package.json
      if (packageJson) {
        const packagePath = path.resolve(localPath, 'package.json');
        if (fs.existsSync(packagePath)) {
          const rawPackage = require(packagePath);
          const curPackage = { ...rawPackage, ...packageJson };

          fs.writeFileSync(packagePath, JSON.stringify(curPackage, null, 2));
        }
      }

      // 删除文件
      if (Array.isArray(deleteFiles) && deleteFiles.length > 0) {
        deleteFiles.forEach((filename) => {
          const filepath = path.resolve(localPath, filename);
          deleteFile(filepath);
        });
      }

      resolve();
    } catch (err) {
      reject(err);
    }
  });
}

module.exports = main;
